package cn.didi.feidi.androidorder.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.SearchGoodsActivity;
import cn.didi.feidi.androidorder.adapter.MainHomePageRecyclerViewAdapter;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.assembly.FeiDiFilterFragmentDialog;
import cn.didi.feidi.androidorder.assembly.FeidiActionBar;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.databinding.FragmentMainHomePageBinding;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.WaterBucket;



/**
 * Created by jinxiong on 2017/8/19.
 */

public class HomePageFragment extends FeiDiMainBaseFragment{

    private static final String TAG = "HomePageFragment";
//    /** Standard activity result: operation succeeded. */
//    public static final int RESULT_OK           = -1;
    FragmentMainHomePageBinding binding;
    MainHomePageRecyclerViewAdapter adapter;
    ArrayList<WaterBucket> waterBuckets;
    private boolean loadMoreFlag;
    private float startPrice = 0;
    private float endPrice = Float.MAX_VALUE;
    private int nextPage;
    private boolean isLoading;


    @Override
    protected void clearSwipeRefreshLayout() {
        isLoading = false;
        loadMoreFlag = false;
        if (binding.homePageSwipeRefreshLayout.isRefreshing()) {
            binding.homePageSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        waterBuckets = new ArrayList<>();
        adapter = new MainHomePageRecyclerViewAdapter(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.getCollectionsFromDb();
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_home_page, container, false);
        nextPage = 1;
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {
        binding.homePageRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        binding.homePageRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        getDataFromNet();
    }


    public void getDataFromNet() {

        if (isLoading) {
            return;
        }
        isLoading = true;

        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("pageNum", String.valueOf(nextPage));
        parameters.put("pageSize", "10");
        parameters.put("lowPrice", String.valueOf(((int) startPrice)));
        parameters.put("highPrice", String.valueOf(((int) endPrice)));

        String url;

        if (!UserManager.isBingAccount()) {

            url = Api.GET_WATER_BUCKET_BY_PRICE_NO_TOKEN;
        } else {
            //登陆了
            parameters.put("userId", UserManager.getUserId());
            parameters.put("token", UserManager.getToken());
            url = Api.GET_WATER_BUCKET_BY_PRICE;
        }


        executeRequest(new AppActionRequest<>(url, parameters, new TypeToken<ApiResponse<List<WaterBucket>>>() {
        }.getType(),
                new ActionCallbackListener<List<WaterBucket>>() {
                    @Override
                    public void onSuccess(String message, List<WaterBucket> data) {


                        Log.d(TAG, "onSuccess: " + message);
                        if (loadMoreFlag) {
                            loadMoreFlag = false;
                            if (data == null) {
                                Toast.makeText(mActivity, "已无更多数据", Toast.LENGTH_SHORT).show();
                            } else {
                                adapter.addWaterBuckets((ArrayList<WaterBucket>) data);
                            }
                        } else {
                            adapter.setWaterBuckets((ArrayList<WaterBucket>) data);
                        }

                        if (binding.homePageSwipeRefreshLayout.isRefreshing()) {
                            binding.homePageSwipeRefreshLayout.setRefreshing(false);
                        }

                        nextPage++;
                        isLoading = false;

                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "onFailure: " + message);

                        if (loadMoreFlag) {
                            loadMoreFlag = false;
                        }
                        if (binding.homePageSwipeRefreshLayout.isRefreshing()) {
                            binding.homePageSwipeRefreshLayout.setRefreshing(false);
                        }
                        isLoading = false;
                    }
                }));
    }

    @Override
    protected void addListener() {
        binding.homePageSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                nextPage = 1;
                getDataFromNet();

            }
        });

        binding.homePageRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


                if (adapter.getItemCount() < ((nextPage - 1) * 10)) {
//                    Toast.makeText(mActivity, "已无更多数据", Toast.LENGTH_SHORT).show();
                    return;
                }


                if (!isLoading) {

                    if (!loadMoreFlag) {
                        LinearLayoutManager manager = (LinearLayoutManager) binding.homePageRecyclerView.getLayoutManager();

                        if (manager.findLastCompletelyVisibleItemPosition() == adapter.getItemCount() - 1) {

                            if (!isMultiplicationClick()) {
                                loadMoreFlag = true;
                                if (!binding.homePageSwipeRefreshLayout.isRefreshing()) {
                                    binding.homePageSwipeRefreshLayout.setRefreshing(true);
                                }
                                getDataFromNet();
                            }

                        }
                    }
                }
            }
        });

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FeiDiFilterFragmentDialog dialog = new FeiDiFilterFragmentDialog();
                Bundle bundle = new Bundle();
                bundle.putSerializable("startPrice", startPrice);
                bundle.putSerializable("endPrice", endPrice);
                dialog.setArguments(bundle);

                dialog.setCallBack(new FeiDiFilterFragmentDialog.CallBack() {
                    @Override
                    public void callBack(float startPrice, float endPrice) {
                        HomePageFragment.this.startPrice = startPrice;
                        HomePageFragment.this.endPrice = endPrice;
                        Log.d(TAG, "callBack: start  " + startPrice + " end   " + endPrice);
                        nextPage = 1;
                        getDataFromNet();
                    }

                });

                dialog.show(getChildFragmentManager(), "");
            }
        };

        binding.homePageFilterIv.setOnClickListener(onClickListener);
        binding.homePageFilterTv.setOnClickListener(onClickListener);


        binding.homePageSearchParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(), SearchGoodsActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void actionBarSetting(FeidiActionBar view) {
        view.setVisibility(View.VISIBLE);
        view.getFallbackView().setVisibility(View.GONE);
        view.getMessageView().setVisibility(View.INVISIBLE);
        view.getSettingView().setVisibility(View.INVISIBLE);
        view.getScanCodeView().setVisibility(View.VISIBLE);
        view.setTitleText("首页");
        view.setScanCodeView(View.VISIBLE);

        view.getScanCodeView().setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent openCameraIntent = new Intent(getContext(),CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
        }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.homePageSwipeRefreshLayout.setOnRefreshListener(null);
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
